﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using gd.ViewModel.ExcelImport;
using gd.Utils.JQuery;
using gd.IBiz;
using System.Data;

namespace gd.Biz.ExcelImport
{
    /// <summary>
    /// Excel导入服务
    /// </summary>
    public class ExcelImportBiz
    {
        private Config _config;
        private IExcelImport _implement;

        /// <summary>
        /// 获取配置信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Config LoadConfig(string id, object obj)
        {
            if (_config == null)
            {
                // 加载配置信息
                _config = new Config()
                {
                    View = "~/Views/ExcelImport/Demo/MenuImport.cshtml"
                };
                // 从配置信息的TypeName反射出实现类
                _implement = new Impl.Demo.MenuImport();
                // 获取导入视图额外需要的数据
                _config.ViewData = _implement.GetViewData(obj);
                // 默认导入视图
                if (string.IsNullOrWhiteSpace(_config.View) == true)
                {
                    // 一般没有特殊导入要求，直接用默认导入视图就行了
                    _config.View = "~/Views/ExcelImport/_ExcelImportForm.cshtml";
                }
            }
            return _config;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private IExcelImport GetImplement(string id)
        {
            if (_implement == null)
            {
                var config = this.LoadConfig(id, null);
                // 从配置信息的TypeName反射出实现类
                _implement = new Impl.Demo.MenuImport();
            }
            return _implement;
        }

        /// <summary>
        /// 检测用户是否有当前数据导入权限
        /// </summary>
        /// <param name="id"></param>
        /// <param name="usrId"></param>
        /// <returns></returns>
        public bool CheckRole(string id, int usrId)
        {
            var hasRole = false;
            // 忽略管理员
            if (usrId == 1)
            {
                hasRole = true;
            }
            else
            {
                // check

                // 演示版暂时先忽略权限判断
                hasRole = true;
            }
            return hasRole;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="usrId"></param>
        /// <param name="formObj"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public jqGrid<ResultRow> ImportCheck(string id, int usrId, object formObj, string fileName)
        {
            var model = new jqGrid<ResultRow>();
            if (this.CheckRole(id, usrId) == true)
            {
                var data = this.GetData(id, fileName);
                var impl = this.GetImplement(id);
                var importResult = impl.ImportCheck(id, formObj, data);

                model.Status = importResult.Success;
                model.Message = importResult.Message;
                model.JsonData = importResult.Rows;

                model.TotalPage = 1;
                model.CurrentPage = 1;
                model.TotalRecord = model.JsonData.Count;
            }
            else
            {
                model.Status = false;
                model.Message = "没有权限";
            }
            return model;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="usrId"></param>
        /// <param name="formObj"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public jqGrid<Result> ImportStart(string id, int usrId, object formObj, string filePath)
        {
            // 1.判断当前配置是否需要检测后导入
            // 1.1. 需要检测：如果检测不通过是否忽略并执行
            // 1.2. 无需检测则继续下一步
            // 2. 如果需要检测，那么判断一下是否已经检测过了
            // 2.1. 如果未检测就导入这是不允许的
            // 2.2. 无需检测则直接执行导入

            var model = new jqGrid<Result>();
            if (this.CheckRole(id, 1) == true)
            {
                // to do
            }
            else
            {
                model.Status = false;
                model.Message = "没有权限";
            }
            return model;
        }

        #region 获取表格数据源
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public IList<object> GetData(string id, string fileName)
        {
            var dt = this.ReadExcel(fileName);
            var list = this.TableToList(id, dt);
            return list;
        }

        /// <summary>
        /// 读取Excel数据
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private DataTable ReadExcel(string fileName)
        {
            // 用 NOPI 读取Excel表格

            // 这里暂时先demo一下
            var dt = new DataTable();
            dt.Columns.Add("菜单名称");
            dt.Columns.Add("地址"); 
            for (int i = 0; i < 10; i++)
            {
                var row = dt.NewRow();
                row["客户姓名"] = "客户" + i;
                row["电话"] = "13333333" + i;
                dt.Rows.Add(row);
            }
            return dt;
        }

        /// <summary>
        /// Excel转换成IList
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        private IList<object> TableToList(string id, DataTable dt)
        {
            IList<object> list = new List<object>();
            foreach (DataRow row in dt.Rows)
            {
                // 反射对象以及特性什么的，然后根据表格列名对应的字段赋值

                // 这里暂时先demo一下
                var data = new gd.ViewModel.ExcelImport.UserModule.CustomerExcelRow()
                {
                    Name = row["客户姓名"].ToString(),
                    Tel = row["电话"].ToString()
                };
                list.Add(data);
            }
            return list;
        }
        #endregion 获取表格数据源

        /// <summary>
        /// 下载模板
        /// </summary>
        /// <param name="configId"></param>
        /// <returns></returns>
        public void DownloadTemplateFile(string id)
        {
            // 1.读取配置信息
            // 2.读取模板文件
            // 3.直接输出模板文件，或返回Stream给控制器后return File(模板文件)

            #region 测试
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            HttpContext.Current.Response.Charset = "Utf-8";
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".xls");
            var sbHtml = new StringBuilder();
            sbHtml.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
            sbHtml.AppendLine("<table cellspacing=\"0\" cellpadding=\"5\" rules=\"all\" border=\"1\">");
            //写出列名
            sbHtml.AppendLine("<tr style=\"background-color: #FFE88C;font-weight: bold; white-space: nowrap;\">");
            sbHtml.AppendLine("<td>列1</td>");
            sbHtml.AppendLine("<td>列2</td>");
            sbHtml.AppendLine("<td>列3</td>");
            sbHtml.AppendLine("</tr>");
            sbHtml.AppendLine("<tr>");
            sbHtml.AppendLine("<td>1</td>");
            sbHtml.AppendLine("<td>2</td>");
            sbHtml.AppendLine("<td>3</td>");
            sbHtml.AppendLine("</tr>");
            sbHtml.AppendLine("</table>");
            HttpContext.Current.Response.Write(sbHtml.ToString());
            HttpContext.Current.Response.End();
            #endregion
        }

        /// <summary>
        /// 下载结果
        /// </summary> 
        /// <param name="resultId"></param>
        public void DownloadResultFile(string resultId)
        { 
            // 1.读取配置信息
            // 2.获取结果数据（MemoryStream）
            // 3.直接输出结果文件，或return File(FileStream, "下载文件类型", "文件名.后缀");

        }
    }
}
